<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="dateTime" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.unionOrderId" :placeholder="'转账/商户/渠道订单号'" :msg="vdata.searchData.unionOrderId" />
        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="商户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />

        <jeepay-text-up v-model:value="vdata.searchData.appId" :placeholder="'应用AppId'" :msg="vdata.searchData.appId" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="转账状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">订单生成</a-select-option>
            <a-select-option value="1">转账中</a-select-option>
            <a-select-option value="2">转账成功</a-select-option>
            <a-select-option value="3">转账失败</a-select-option>
          </a-select>
        </a-form-item>
        
        <JeepaySelect ref="ifCodeRef" placeholder="支付接口" :reset="isReset">
          <a-select v-model:value="vdata.searchData.ifCode" @change="ifCodeRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <a-select-option :value="item.ifCode">{{ item.ifName }}[{{ item.ifCode }}]</a-select-option>
            </template>
          </a-select>
        </JeepaySelect>
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="transferId"
        :tableRowCrossColor="true"
        :statisticsIsShow="$access('ENT_TRANSFER_ORDER_COUNT')"
        :autoRefTableConfig="{defaultOpen: true, interval: 180}"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in orderCountList" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
                <span v-if="item.isAmount">元</span>
              </div>
            </div>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'amount'">
            <b>￥{{ record.amount/100 }}</b>
          </template>

          <template v-if="column.key == 'mchFeeRate' && typeof record.mchOrderFeeAmount != 'undefined'">
            <a-popover placement="top">
              <template #title> <b>￥转账手续费</b></template>
              <template #content>
                {{ record.mchFeeRate }}
              </template>
              <b>￥{{ record.mchOrderFeeAmount/100 }}</b>
            </a-popover>
          </template>

          <template v-if="column.key === 'state'">
            <a-tag
              :key="record.state"
              :color="record.state === 0?'blue':record.state === 1?'orange':record.state === 2?'green':'volcano'"
            >
              {{ record.state === 0?'订单生成':record.state === 1?'转账中':record.state === 2?'转账成功':record.state === 3?'转账失败':record.state === 4?'任务关闭':'未知' }}
            </a-tag>
          </template>

          <template v-if="column.key === 'orderNo'">
            <div class="order-list">
              <p><span style="color:#729ED5;background:#e7f5f7">转账</span>{{ record.transferId }}</p>
              <p style="margin-bottom: 0;">
                <span style="color:#56cf56;background:#d8eadf">商户</span>
                <a-tooltip v-if="record.mchOrderNo.length > record.transferId.length" placement="bottom" style="font-weight: normal;">
                  <template #title>
                    <span>{{ record.mchOrderNo }}</span>
                  </template>
                  {{ changeStr2ellipsis(record.mchOrderNo, record.transferId.length) }}
                </a-tooltip>
                <span v-else style="font-weight: normal;">{{ record.mchOrderNo }}</span>
              </p>
              <p v-if="record.channelOrderNo" style="margin-bottom: 0;margin-top: 10px">
                <span style="color:#fff;background:#E09C4D">渠道</span>
                <a-tooltip v-if="record.channelOrderNo.length > record.transferId.length" placement="bottom" style="font-weight: normal;">
                  <template #title>
                    <span>{{ record.channelOrderNo }}</span>
                  </template>
                  {{ changeStr2ellipsis(record.channelOrderNo, record.transferId.length) }}
                </a-tooltip>
                <span v-else style="font-weight: normal;">{{ record.channelOrderNo }}</span>
              </p>
            </div>
          </template>

          <template v-if="column.key === 'ifCode'">
            <span>{{ record.ifName }} ({{ record.ifCode }})</span>
          </template>

          <template v-if="column.key === 'op'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_TRANSFER_ORDER_VIEW')" type="link" @click="detailFunc(record.transferId)">详情</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <!-- 订单详情 页面组件  -->
    <TransferOrderDetail ref="transferOrderDetail" />
  </page-header-wrapper>
</template>
<script setup lang="ts">

import TransferOrderDetail from './TransferOrderDetail.vue'
import { API_URL_TRANSFER_ORDER_LIST, req, $exportExcel, exportExcelUrl, API_URL_IFDEFINES_LIST, $transferOrdersCount } from '@/api/manage'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import fileDownload from 'js-file-download'

// 导入全局函数
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

// infoTable组件
const infoTable = ref()
const transferOrderDetail = ref()
const ifCodeRef = ref()
const dateRangePicker = ref()
let isReset = ref(0) // 下拉搜索框是否重置

let orderCountList:any = ref([]) // 数据统计数组

  // eslint-disable-next-line no-unused-vars
  const tableColumns = ref([
    { key: 'orderNo', title: '订单号'},
    { key:'amount', title: '转账金额' },
    {key:'mchFeeRate', title: '手续费'},
    { title: '商户名称', dataIndex: 'mchName' },
    // { title: '渠道订单号', dataIndex: 'channelOrderNo' },
    { key: 'ifCode', title: '支付接口'},
    { title: '收款账号', dataIndex: 'accountNo' },
    { title: '收款人姓名', dataIndex: 'accountName'},
    { title: '转账备注', dataIndex: 'transferDesc' },
    { key:'state', title: '状态' },
    { title: '创建日期', dataIndex: 'createdAt' },
    { key: 'op', title: '操作',  fixed: 'right', align: 'center' }
  ])

  const vdata : any = reactive({
          btnLoading: false,
          searchData: {queryDateRange: 'today'} as any,
  })

  onMounted( () => {
    if($access('ENT_PC_IF_DEFINE_LIST')){
      req.list(API_URL_IFDEFINES_LIST, {state:1}).then((res) => {
        vdata.ifCodeList = res
      })
    }
    getOrderCount()
  })

  // 数据统计
  const getOrderCount = () => {

    if(!$access('ENT_TRANSFER_ORDER_COUNT')){
      return false
    }

    $transferOrdersCount(vdata.searchData).then( res => {
      orderCountList.value = [ 
        {title: '转账金额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.transAmount / 100).toFixed(2)},
        {type: 'line'},
        {title: '转账笔数', content: res.transCount, isAmount: false, count: res.allCount, detail: true},
        {type: 'line'},
        {title: '手续费金额',symbol: 'sub', isAmount: true, content: (res.mchOrderFeeAmount / 100).toFixed(2)},
      ]
    })
  }

  function onReset(){
    isReset.value++ // 下拉搜索框重置
    //重置搜索内容
    dateRangePicker.value.returnSelectModel()
    vdata.searchData = { queryDateRange: 'today' }
  }
    
  function queryFunc () {
    vdata.btnLoading = true
    infoTable.value.refTable(true)
  }
  // 请求table接口数据
  function reqTableDataFunc (params) {
    return req.list(API_URL_TRANSFER_ORDER_LIST, params)
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    getOrderCount()

    infoTable.value.refTable(true)
  }
  function detailFunc (recordId) {
    transferOrderDetail.value.show(recordId)
  }
  function changeStr2ellipsis (orderNo, baseLength) {
    const halfLengh = baseLength / 2
    return orderNo.substring(0, halfLengh - 1) + '...' + orderNo.substring(orderNo.length - halfLengh, orderNo.length)
  }

function tableExportFunc(){
  return $exportExcel(exportExcelUrl.transferOrder, Object.assign({}, vdata.searchData, {'pageSize': -1})).then(res => {
      fileDownload(res.data, '转账订单.xlsx')
  }).catch ((error) =>{console.log(error)} )
}
</script>
<style lang="less" scoped>
.order-list {
  -webkit-text-size-adjust:none;
  font-size: 12px;
  display: flex;
  flex-direction: column;

  p {
    white-space:nowrap;
    span {
      display: inline-block;
      font-weight: 800;
      height: 16px;
      line-height: 16px;
      width: 35px;
      border-radius: 5px;
      text-align: center;
      margin-right: 2px;
    }
  }
}
</style>
